package Server;

/**
 *
 * @author Daniel
 */
import java.net.*;
import java.io.*;
import java.util.*;

public class Client implements Runnable
{
    private Socket connection;
    private Thread clientThread;
    private BufferedOutputStream outStream;
    private OutputStreamWriter outStreamWrite;
    
    public Client(Socket connection, int id)
    {
        //Construct our we client handler
        this.connection     = connection;
        this.clientThread   = new Thread(this, "" + id);
        try
        {
            this.outStream      = new BufferedOutputStream(this.connection.getOutputStream());
            this.outStreamWrite = new OutputStreamWriter(this.outStream, "US-ASCII");
        }
        catch(IOException ioe)
        {
            System.out.println("IO exception while attempting to setup outputstream");
            System.out.println("Error: " + ioe);
            System.exit(3);
        }          
        this.clientThread.start();
    }
    
    public void run()
    {
        //Handle the sh*t out of this mofo.
        System.out.println("Client thread started.");
        //Make first contact
        this.initConn();
        //Wait for message and respond
    }
    
    public Socket getSocket()
    {
        return this.connection;
    }
    
    private boolean writeMessage(String message)
    {
        try
        {            
            this.outStreamWrite.write(message);
            this.outStreamWrite.flush();
        }
        catch(IOException ioe)
        {
            System.out.println("IOException when trying to write message");
            System.out.println("IOE from thread/client: " + this.clientThread.getId());
            System.out.println("Error: " + ioe);
            return false;
        }
        return true;
    }
    
    private void initConn()
    {
        //Send client it's ID and confirm connection
        this.writeMessage("HiHiHi Dainius!");
    }
}
